
package com.contactdemo;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.contactdemo.bean.Contact;

import java.util.Collections;
import java.util.List;

/**
 * 列表适配器
 *
 * @author kymjs (http://www.kymjs.com/) on 9/16/15.
 */
public class ContactAdapter extends BaseQuickAdapter<Contact,BaseViewHolder> implements SectionIndexer {



    public ContactAdapter(int layoutResId, List<Contact> datas) {
        super(layoutResId, datas);
        Collections.sort(datas);
    }

    @Override
    protected void convert(BaseViewHolder holder, Contact item) {
        int position = holder.getLayoutPosition();
        Log.d("xxx","当前postion:"+position);
        holder.setText(R.id.contact_title, item.getName());
        ImageView headImg = holder.getView(R.id.contact_head);
        TextView tvLetter = holder.getView(R.id.contact_catalog);

        //如果是第0个那么一定显示#号
         if (position == 0) {
            tvLetter.setVisibility(View.VISIBLE);
            tvLetter.setText("#");
        } else {

            //如果和上一个item的首字母不同，则认为是新分类的开始
            Contact prevData = getItem(position - 1);
            if (item.getFirstChar() != prevData.getFirstChar()) {
                tvLetter.setVisibility(View.VISIBLE);
                tvLetter.setText("" + item.getFirstChar());
            } else {
                tvLetter.setVisibility(View.GONE);
            }
        }
    }


    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        Contact item = getItem(position);
        return item.getFirstChar();
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getItemCount(); i++)
        {
            char firstChar = getItem(i).getFirstChar();
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public Object[] getSections() {
        return null;
    }


}
